import json
import pandas as pd
from scipy import signal
import numpy as np
import talib
import matplotlib.pyplot as plt
from kbarutils.support import support
from utils.file_util import createPath

kSupport=support()

def series2List(series,reverse=False):
    """
    series转list
    reverse：是否反转
    """
    listArr=[]

    if(isinstance(series,pd.Series)):
        newList=series.to_list()
        if(reverse):
            newList.reverse()
        return listArr.append(newList)

    if(isinstance(series,list)):
        for index in range(len(series)):
            listItem=series[index].to_list()
            if(reverse):
                listItem.reverse()
            listArr.append(listItem)
    return listArr


def getFrameValue(frame,keyValue):
    """
    dataframe取值
    """
    seriesArray=[]
    if(isinstance(frame,pd.Series)):
        return seriesArray.append(frame[keyValue])
        
    if(isinstance(frame,list)):
        for index in range(len(frame)):
            seriesArray.append(frame[index][keyValue])
    return seriesArray


def getExtremun(numArray,test=False):
    """
    求连续曲线的极值
     格式 {"15":{"max":string,"min":string}}
    """

    extremunMap={}
    for index in range(len(numArray)):
        if isinstance(numArray[index],list):
            x=[]
            num=0
            for item in numArray[index]:
                num=num+1
                x.append(num)
    
            x = np.array(x)
            y = np.array(numArray[index])
            f1 = np.polyfit(x, y, 25)
            p1 = np.poly1d(f1)
            yvals = p1(x)

            maxIndex=signal.argrelextrema(yvals, np.greater)[0]
            minIndex=signal.argrelextrema(yvals, np.less)[0]

            maxValue=",".join(map(str,[len(x)-index for index in maxIndex[::-1]]))
            minValue=",".join(map(str,[len(x)-index for index in minIndex[::-1]]))

            chartTitle=""
            valueMap={"max":maxValue,"min":minValue}

            if index==0:
                extremunMap["5"]=valueMap
                chartTitle="5分钟"
            elif index==1:
                extremunMap["15"]=valueMap
                chartTitle="15分钟"
            elif index==2:
                extremunMap["30"]=valueMap
                chartTitle="30分钟"
            elif index==3:
                extremunMap["60"]=valueMap
                chartTitle="60分钟"
            elif index==4:
                extremunMap["4h"]=valueMap
                chartTitle="4小时"
            elif index==5:
                extremunMap["day"]=valueMap
                chartTitle="日线图"

            if test:
                filePath='C:/Users/Administrator/Desktop/extremun/'
                plt.plot(x, y, '*',label='original values')
                plt.plot(x, yvals, 'r',label='polyfit values')
                plt.xlabel('x axis')
                plt.ylabel('y axis')
                plt.legend(loc=4)
                plt.title(chartTitle)
                plt.plot(maxIndex,yvals[signal.argrelextrema(yvals, np.greater)],'o', markersize=10)  #极大值点
                plt.plot(minIndex,yvals[signal.argrelextrema(yvals, np.less)],'+', markersize=10)  #极小值点
                plt.savefig(createPath(filePath,0)+chartTitle+'.jpg')
                plt.show()
    return extremunMap
    

def getListArrToStr(listValue):
    """
    list字符串拼接
    """

    supportStr=""
    for index in range(len(listValue)):
        supportStr=supportStr+",".join(map(str,[index for index in kSupport.KmeansFix(listValue[index])]))+";"
    return supportStr